package com.xja.webchat.controller;

import com.xja.webchat.entity.Chatuser;
import com.xja.webchat.entity.Message;
import com.xja.webchat.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MessageController {
    @Autowired
    private MessageService messageService;

    @GetMapping("/{fromid}/readMessage")
    public Map<String,Object> readMessage(@PathVariable("fromid") Integer fromid, HttpSession session){
        Map<String,Object> resuMap=new HashMap<>();
        try {

            Chatuser loginUser = (Chatuser)session.getAttribute("loginUser");
            if(loginUser==null){
                resuMap.put("status","null");
                return resuMap;
            }
            Map<String,Integer> map=new HashMap<>();
            map.put("fromid",fromid);
            map.put("toid",loginUser.getId());
            List<Message> messageList = messageService.selectMassageList(map);
            resuMap.put("messageList",messageList);
            return resuMap;
        }catch (Exception e){
            e.printStackTrace();
        }
        resuMap.put("status","false");
        return resuMap;
    }
    @PostMapping("message")
    public Map<String,Object> addmessage(@RequestBody Message message,HttpSession session){
        Map<String,Object> resuMap=new HashMap<>();
        try {
           Chatuser loginUser= (Chatuser)session.getAttribute("loginUser");
            message.setType(1);
            message.setTime(new Date());
            message.setStatus(0);
            message.setFromid(loginUser.getId());
            messageService.addMessage(message);

            resuMap.put("status","true");
            return resuMap;

        }catch (Exception e){
            e.printStackTrace();
        }
        resuMap.put("status","false");
        return resuMap;
    }
}
